package com.situ.mall.controller;

import com.situ.mall.pojo.vo.CategoryVO;
import com.situ.mall.service.ICategoryService;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    private Map<String, List<CategoryVO>> map = new HashMap<>();

    @RequestMapping("/listAll")
    public Result listAll() {
        //1、首先查询Redis缓存
        List<CategoryVO> list = redisTemplate.opsForList().range("categoryList", 0, -1);
        //2、Redis缓存中没有
        if (ObjectUtils.isEmpty(list)) {
            //3、查询数据库
            list = categoryService.listAll();
            //4、从数据库查询之后，更新到Redis缓存中
            redisTemplate.opsForList().rightPushAll("categoryList", list);

        }
        return Result.ok(list);
    }

    @RequestMapping("/listAll2")
    public Result listAll2() {
        //1、首先查询Map缓存
        List<CategoryVO> list = map.get("categoryList");
        //2、Map缓存中没有
        if (ObjectUtils.isEmpty(list)) {
            //3、查询数据库
            list = categoryService.listAll();
            //4、从数据库查询之后，更新到Map缓存中
            map.put("categoryList", list);

        }
        return Result.ok(list);
    }
}